<?php
namespace app\home\controller;
use \think\Request;
use \think\Validate;
use \think\Session;
use \think\Controller;

class Student extends Controller
{

	/*
	学生登录做题
	 */
    public function login()
    {
    
    	if (Request::instance()->isPut()) {
            //登录成功 跳转到试卷列表页

            $data = Request::instance()->put();
//            dump($data);
    		$validate = new Validate([
	            'phone' => 'require|min:11|max:11',
	            'password' => 'require|min:6',
        	]);

            if(!$validate->check($data)){
                $this->error($validate->getError());
            }
	        $data=[
	            'phone'=>$data['phone'],
	            'password'=>md5($data['password']),
	        ];

    		//查询当前用户名和密码是否存在数据
    		$student = new \app\home\model\Student();
            $result = $student->where(['phone'=> $data['phone'],'password'=> $data['password']])
                ->find();
    		if ($result) {
                // var_dump($result);
                Session::set('phone',$result['phone']);
                Session::set('id',$result['stuid']);
                return $this->success('登录成功','home/Paper/getList');
    		}else{
    			return $this->error('登录失败');
    		}
    	}else{
    		return $this->fetch();
    	}
    }
    /*
    学生注册
    */
    public function doRegister()
    {

        if (Request::instance()->isPut()) {
            //登录成功 跳转到试卷列表页

            $data = Request::instance()->put();
//            dump($data);
            $validate = new Validate([
                'phone' => 'require|min:11|max:11',
                'password' => 'require|min:6',
            ]);

            if(!$validate->check($data)){
                $this->error($validate->getError());
            }
            $student = new \app\home\model\Student();
            //判断手机号是否已经注册
            $re = $student->where('phone',$data['phone'])
                ->find();
            if($re){
                return $this->error('手机号已注册');
            }
            $data=[
                'phone'=>$data['phone'],
                'password'=>md5($data['password']),
            ];

            //插入数据
            $student->data($data);
            $result = $student->save();

            if ($result) {
                // 注册成功 跳转到登录页面
                return $this->success('注册成功','home/Student/login');
            }else{
                return $this->error('注册失败');
            }
        }else{
            return $this->fetch();
        }
    }
    /*
     * 学生注册页面
     */
    public function register(){
        return $this->fetch();
    }
}
